package fr.sportcom.sportcom.services;

import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.json.JSONObject;

import fr.sportcom.sportcom.model.CustomHttpClient;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class NotifyManagerIntentService extends IntentService {
	
	public final static int ACTION_INVITATION = 0x00000010;
	public final static int ACTION_ALARM = 0x00000100;
	
	private final static String TAG_SERVICE = "fr.sportcom.sportcom.tag.NotifyManagerIntentService";
	private final static String EXTRA_ACTION = "fr.sportcom.sportcom.extra.service.ACTIONS";
	private final static String EXTRA_USER = "fr.sportcom.sportcom.extra.service.USER_ID";

	public static PendingIntent prepareIntent(Context context, int action, int userId) {
		Log.d("ServiceNotify", "prepareIntent");
		Intent i = new Intent(context, NotifyManagerIntentService.class);
		i.putExtra(EXTRA_ACTION, action);
		i.putExtra(EXTRA_USER, userId);
		return PendingIntent.getService(context, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	public NotifyManagerIntentService() {
		super(TAG_SERVICE);
		Log.d("ServiceNotify", "Service manager executé");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int action = intent.getIntExtra(EXTRA_ACTION, 0);
		int userId = intent.getIntExtra(EXTRA_USER, 0);
		if((action & ACTION_INVITATION) == ACTION_INVITATION) {
			// Service invitation
			Intent invIntent = InvitationNotifyIntentService.prepareIntent(this, userId);
			startService(invIntent);
		}
		if((action & ACTION_ALARM) == ACTION_ALARM) {
			// Service alarm
			Intent invIntent = AlarmNotifyIntentService.prepareIntent(this, userId);
			startService(invIntent);
		}
	}
	
	public static JSONObject executeRequest(String funcName, ArrayList<NameValuePair> param) {
		CustomHttpClient request = new CustomHttpClient();
		JSONObject jObj = null;

		try {
			jObj = request.postData(funcName, param);

			if(jObj.getInt("back") != 0) {
				return null;
			}

		} catch (Exception e) {
			return null;
		}
		return jObj;
	}
}
